/*
 * $Id: SubjectGroupManager.java 8 2012-04-28 05:11:23Z forwardly@gmail.com $
 * 
 * Copyright (c) 2001-2008 Accentrix Company Limited. All Rights Reserved.
 * 
 * Accentrix Company Limited. ("Accentrix") retains copyright on all text, source
 * and binary code contained in this software and documentation. Accentrix grants
 * Licensee a limited license to use this software, provided that this copyright
 * notice and license appear on all copies of the software. The software source
 * code is provided for reference purposes only and may not be copied, modified 
 * or distributed.
 * 
 * THIS SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS," WITHOUT ANY WARRANTY OF
 * ANY KIND UNLESS A SEPARATE WARRANTIES IS PURCHASED FROM ACCENTRIX AND REMAINS
 * VALID.  ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. ACCENTRIX SHALL NOT BE LIABLE
 * FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING OR MODIFYING THE
 * SOFTWARE OR ITS DERIVATIVES.
 * 
 * IN NO EVENT WILL ACCENTRIX BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
 * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES,
 * HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE
 * USE OF OR INABILITY TO USE SOFTWARE, EVEN IF ACCENTRIX HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 */
package com.lightsaber.trade.as.service.programme;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lightsaber.trade.as.dao.programme.ProgrammeCodeDao;
import com.lightsaber.trade.as.dao.programme.SubjectGroupDao;
import com.lightsaber.trade.as.dao.programme.SubjectGroupItemDao;
import com.lightsaber.trade.as.entity.programme.ProgrammeCode;
import com.lightsaber.trade.as.entity.programme.SubjectGroup;
import com.lightsaber.trade.as.entity.programme.SubjectGroupItem;
import com.lightsaber.trade.core.dao.BaseDao;
import com.lightsaber.trade.core.service.BaseServiceImpl;

@Service
@Transactional
public class SubjectGroupManager extends BaseServiceImpl<SubjectGroup, String> {

    @Autowired
    SubjectGroupDao subjectGroupDao;
    @Autowired
    ProgrammeCodeDao programmeCodeDao;
    @Autowired
    SubjectGroupItemDao subjectGroupItemDao;
    @Autowired
    ProgrammePlanProjectionTypeManager programmePlanProjectionTypeManager;

    @Override
    protected BaseDao<SubjectGroup, String> getDao() {
        return subjectGroupDao;
    }

    public void save(final String code, SubjectGroup subjectGroup,
            final Map<String, String> selectedCodesMap) {
        String id = "";

        if (StringUtils.isBlank(subjectGroup.getId())) {
            ProgrammeCode programmeCode = programmeCodeDao.getByCode(code);
            subjectGroup.setProgrammeCode(programmeCode);

            try {
                SubjectGroup tmp = subjectGroupDao.findByCodeAndPlanYear(code,
                        subjectGroup.getPlanningExercise());
                if (tmp != null)
                    return;
            } catch (Exception ex) {
                return;
            }
            super.save(subjectGroup);
            id = subjectGroup.getId();

            Set<String> codes = selectedCodesMap.keySet();

            for (String itemCode : codes) {
                SubjectGroupItem item = new SubjectGroupItem();
                programmeCode = programmeCodeDao.getByCode(itemCode);

                item.setSubjectGroup(subjectGroup);
                item.setProgrammeCode(programmeCode);

                subjectGroupItemDao.save(item);
            }

        } else {

            SubjectGroup old = super.get(subjectGroup.getId());
            id = old.getId();

            List<SubjectGroupItem> subjectGroupItems = old.getSubjectGroupItems();

            for (SubjectGroupItem item : subjectGroupItems) {
                String itemCode = item.getProgrammeCode().getCode();

                if (selectedCodesMap.containsKey(itemCode)) {
                    selectedCodesMap.remove(itemCode);
                } else {

                    programmePlanProjectionTypeManager.changeFeederOnDeleteGroupItem(old, item);
                    subjectGroupItemDao.delete(item);
                }
            }

            Set<String> codes = selectedCodesMap.keySet();

            for (String itemCode : codes) {
                SubjectGroupItem item = new SubjectGroupItem();
                ProgrammeCode programmeCode = programmeCodeDao.getByCode(itemCode);

                item.setSubjectGroup(old);
                item.setProgrammeCode(programmeCode);

                subjectGroupItemDao.save(item);
            }

            subjectGroup = old;
        }

        subjectGroupDao.getSession().flush();
        subjectGroupDao.getSession().clear();

        SubjectGroup group = super.get(id);
        programmePlanProjectionTypeManager.changeFeederOnUpdateGroup(group);
    }

    public boolean hasSameSubjectGroup(final String programmeCode, final int planningExercise,
            final String subjectId) {
        try {
            SubjectGroup tmp = subjectGroupDao.findByCodeAndPlanYear(programmeCode,
                    planningExercise);
            if (tmp != null) {
                if (!tmp.getId().equals(subjectId))
                    return true;
            }
        } catch (Exception ex) {
            return true;
        }

        return false;
    }
}
